#/usr/bin/env python2.7
#-*- coding=utf-8 -*-

import re

class HTTP(object):
    def __init__(self, data):
        self.ishttp = False
        if re.match(r'(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) /[^ \r\n]* HTTP/1\.[01]\r\n', data, re.I):
            self.ishttp =  self._httpresolve_(data)
        elif re.match(r'HTTP/1.[01] [\d]+ [^\r\n]+\r\n'):
            self.ishttp = _httpresponse_(data, 'response')

    def _httpresolve_(self, data, httptype = 'request'):
        datasplit = data.split('\r\n\r\n', 1)
        if len(datasplit) == 1:
            return False
        ret = {}
        httphdr = datasplit[0]
        httpdata = datasplit[1]
        if httpdata:
            self.data = httpdata
        hdrs = httphdr.split('\r\n')
        self.header = {}
        if httptype == 'request':
            self._httprequest_(hdrs[0])
        elif httptype == 'response':
            self._httpresponse_(hdrs[0])
        for hdr in hdrs[1:]:
            hdrsplit = hdr.split(': ', 1)
            if len(hdrsplit) == 1:
                continue
            self.header[hdrsplit[0]] = hdrsplit[1]
        return True

    def _httprequest_(self, hdr):
        method, uri, version = hdr.split(' ')
        self.header['Request Method'] = method
        self.header['Request Uri'] = uri
        self.header['Request Version'] = version

    def _httpresponse_(self, hdr):
        version, code, phrase = hdr.split(' ')
        self.header['Request Version'] = version
        self.header['Status Code'] = code
        self.header['Response Phrase'] = phrase

class DNS(object):
    pass
